package android.mobilin;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.gsm.SmsManager;
import android.view.KeyEvent;
import android.view.MotionEvent;

public class StartActivity extends Activity {
    Intent next;
	static DBAdapter db;
	boolean stop;
	
    final Handler handler= new Handler() {
    	public void handleMessage(Message msg) {
    		synchronized(this) {
	    		if(!stop) {
		    		if(msg.getData().getBoolean("success")) {
		    			stop=true;
		    			startActivity(next);
		    			finish();
		    		}
	    		}
    		}
    	}
    };
    
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        next = new Intent(this, Menu.class);
        db=new DBAdapter(this);
        stop=false;
        new StartThread(handler).start();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	synchronized(this) {
	    	if(!stop) {
	    		stop=true;
		    	startActivity(next);
		    	finish();
	    	}
    	}
    	return false;
    } 
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	synchronized(this) {
	    	if(!stop) {
	    		stop=true;
		    	startActivity(next);
		    	finish();
	    	}
    	}
    	return false;
    }
    public static void sendSMS(String number,String message, PendingIntent pi,boolean useServerNum) {
    	if(useServerNum) {
	    	Cursor num=db.query("setting");
	    	if(num!=null) {
	    		int serverno=num.getColumnIndex("server_no");
	    		if(num.moveToNext()) {
	    			number=num.getString(serverno);
	    			num.close();
	    			SmsManager sms = SmsManager.getDefault();
	    			sms.sendTextMessage(number, null, message, pi, null);
	    		}
	    	}
    	}
    	else {
    		SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(number, null, message, pi, null);
    	}
    }    
}

class StartThread extends Thread {
	Handler handler;
	
	public StartThread(Handler handler) {
		this.handler=handler;
	}
	
	public void run() {
		boolean success=false;
		try {
			Thread.sleep(3000);
			success=true;
		} catch (InterruptedException e) {
			success=false;
		}
		Message m=handler.obtainMessage();
		Bundle b=new Bundle();
		b.putBoolean("success", success);	
		m.setData(b);
		handler.sendMessage(m);
	}
}